package com.peng.leetcode.other;

/**
 * NextPermutation
 *
 * @author: lupeng6
 * @create: 2021/1/1 21:53
 */
public class NextPermutation {

    public static void main(String[] args) {
        int[] arr = {1,2,7,4,3,1};
        new NextPermutation().nextPermutation(arr);
        System.out.println(arr);
    }

    public void nextPermutation(int[] nums) {
        int k = -1;
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] < nums[i + 1]) {
                k = i;
                break;
            }
        }
        if (k == -1) {
            reverse(nums, 0, nums.length - 1);
        } else {
            int l = -1;
            for (int i = k + 1; i < nums.length; i++) {
                if (nums[i] > nums[k]) {
                    l = i;
                    break;
                }
            }
            swap(nums, k, l);
            reverse(nums, k + 1, nums.length - 1);
        }
    }

    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            swap(nums, start, end);
            start++;
            end--;
        }
    }

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
